package io.a;

import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.javacv.*;

import java.io.IOException;

public class Main2 {

    /**
     * 拉取指定时长的视频-保存为mp4
     *
     * @param rtspUrl    流地址
     * @param duration   时长（秒）（TimeUnit Seconds）
     * @param outputFile 输出位置
     */
    public static void videoPuller(String rtspUrl, int duration, String outputFile) {
        // 创建抓取器
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(rtspUrl);
        try {
            grabber.start();
            // 创建录制器-设置的文件保存位置以及视频画面的宽度和高度
            FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, grabber.getImageWidth(), grabber.getImageHeight());
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); // 设置视频编解码器
            recorder.setFormat("mp4"); // 设置视频输出格式

            // 设置音频相关参数
            recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC);
            //这里直接写2以及后续写固定值也可以，当然我们可以从grabber对象中get出来
            //grabber.getAudioChannels();
            // recorder.setAudioChannels(grabber.getAudioChannels());
            recorder.setAudioChannels(2);
            //grabber.getSampleRate();
            recorder.setSampleRate(44100);
            //grabber.getAudioBitrate();
            recorder.setAudioBitrate(192000);
            recorder.start();

            Frame frame;
            long startTime = System.currentTimeMillis();
            long endTime = startTime + (duration * 1000);

            while ((frame = grabber.grabFrame()) != null && System.currentTimeMillis() <= endTime) {
                recorder.record(frame);
            }
            recorder.stop();
            grabber.stop();
            recorder.close();
            grabber.close();
        } catch (FrameGrabber.Exception | FrameRecorder.Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        videoPuller("rtsp流地址",60, "D:\\va\\a.mp4");
    }

}
